import React, { useState, useEffect, useCallback } from "react";
import { Table, Input, Popconfirm, Form, message } from "antd";
import request from "@/utils/request";
import "../css/tagList.css";

function Taglist() {
  const [form] = Form.useForm();
  const [originData, setlist] = useState([]);
  const [query, setQuery] = useState({}); // 搜索条件
  const [editingKey, setEditingKey] = useState("");
  const isEditing = (record) => record._id === editingKey; // 是否是编辑状态

  // 获取表单数据
  const getList = useCallback(async () => {
    const { data: res } = await request.get("/tag", { params: query });
    if (res.code !== 200) return message.error("获取数据失败！");
    setlist(res.data);
  }, []);
  useEffect(() => {
    getList();
  }, []);
  // 编辑按钮
  const edit = (record) => {
    form.setFieldsValue({
      title: "",
      descript: "",
      ...record,
    });
    setEditingKey(record._id);
  };
  // 编辑的取消按钮
  const cancel = () => {
    setEditingKey("");
  };
  // 编辑的保存按钮
  const save = async (id) => {
    // 在这里发axios请求
    const row = await form.validateFields();
    // console.log(row);
    await request.put("/tag/" + id, row).then(({ data }) => {
      // console.log('row',row);
      if (data.code === 200) {
        message.success("修改成功");
      }
      getList();
    });

    setEditingKey("");
  };

  // 确认删除按钮
  const confirm = useCallback((id) => {
    request.delete("/tag/"+id).then((data)=>{
      console.log('detele',data);
      if (data.code === 200) {
        message.success("删除成功");
      }
      getList();
    })

  });

  // 编辑表格行 editing：编辑状态（布尔值） dataIndex：字段 title：表头名字 inputType:输入框字段类型  record：单条数据
  const EditableCell = ({
    editing,
    dataIndex,
    title,
    record,
    index,
    children,
    ...restProps
  }) => {
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{ margin: 0 }}
            rules={[{ required: true, message: `请输入 ${title}!` }]}
          >
            <Input />
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };
  // 定义渲染表格列
  const columns = [
    {
      title: "#",
      width: "5%",
      render: (text, record, index) => index + 1,
    },
    {
      title: "标题",
      dataIndex: "lable",
      width: "25%",
      editable: true,
    },
    {
      title: "描述",
      dataIndex: "describe",
      width: "60%",
      editable: true,
    },
    {
      title: "编辑",
      // record当前行的数据
      render: (row, record) => {
        const editable = isEditing(record);
        return editable ? (
          <>
            <span stype={{ marginLeft: 30 }}>
              <a onClick={() => save(record._id)} style={{ marginRight: 8 }}>
                保存
              </a>
              <a onClick={cancel}>取消</a>
            </span>
          </>
        ) : (
          <>
            <a
              stype={{ marginLeft: 30 }}
              disabled={editingKey !== ""}
              onClick={() => edit(record)}
            >
              修改
            </a>
            <Popconfirm
              placement="top"
              title="确认删除吗？"
              onConfirm={()=>{
                confirm(row._id)
              }}
              okText="确定"
              cancelText="取消"
            >
              <a style={{ marginLeft: 15 }}>删除</a>
            </Popconfirm>
          </>
        );
      },
    },
  ];

  const mergedColumns = columns.map((item) => {
    if (!item.editable) {
      return item;
    }
    return {
      ...item,
      onCell: (record) => ({
        record,
        dataIndex: item.dataIndex,
        title: item.title,
        editing: isEditing(record),
      }),
    };
  });

  return (
    <Form form={form} component={false}>
      <Table
        components={{ body: { cell: EditableCell } }}
        rowKey={(row) => row._id}
        bordered
        dataSource={originData}
        columns={mergedColumns}
      />
    </Form>
  );
}
export default Taglist;
